<template>
  <div class="user-list">
    <search-list
      ref="categoryList"
      :api-url="$url.MallCategoryList"
      :option="searchOpt"
      :itemPerRow="6"
      :beforeQuery="beforeQuery"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="title" label="分类名称"></el-table-column>
      <el-table-column prop="sortnum" label="排序"></el-table-column>
      <el-table-column prop="logo" label="图标">
        <template slot-scope="scope">
          <img v-if="scope.row.logo" :src="scope.row.logo" alt="" class="avatar goods" />
        </template>
      </el-table-column>
      <el-table-column prop="enabled" label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.enabled" type="success">启用</span>
          <span v-else type="danger">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150px">
        <template slot-scope="scope">
          <el-button type="text" @click="edit(scope.row)">编辑</el-button>
          <!-- 1-启用，2-禁用 -->
          <el-button type="text" v-if="!scope.row.enabled" @click="isOnline(scope.row, 1)">
            启用
          </el-button>
          <el-button type="text" v-else @click="isOnline(scope.row, 0)">禁用</el-button>
          <el-button type="danger" @click="delItem(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <div slot="btn-after" class="btn-after">
        <el-button type="primary" @click="addCate">
          添加分类
        </el-button>
        <el-button type="primary" @click="delItem" :disabled="selectedData.length < 1">
          批量删除
        </el-button>
      </div>
    </search-list>
    <!-- 这里是添加分类 -->
    <el-dialog
      :visible="dialogVisibleCate"
      title="添加分类"
      width="60%"
      @close="dialogClose"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <el-form
        :model="categoryForm"
        :rules="categoryRule"
        label-width="80px"
        label-position="right"
        ref="categoryForm"
      >
        <el-form-item prop="title" label="分类名称">
          <el-input v-model="categoryForm.title"></el-input>
        </el-form-item>
        <el-form-item prop="logo" label="图标">
          <el-row>
            <upload-resource
              is-public
              @upload="(img) => $set(categoryForm, 'logo', img.url)"
              :folder="'mallImg' + '/' + imgDate"
            ></upload-resource>
          </el-row>
          <el-row v-if="this.categoryForm.logo">
            <img style="max-height: 200px;" :src="this.categoryForm.logo" alt="" />
          </el-row>
          <el-button
            @click="$set(categoryForm, 'logo', '')"
            type="danger"
            v-if="this.categoryForm.logo"
          >
            删除图片
          </el-button>
        </el-form-item>
        <el-form-item prop="sortnum" label="分类排序">
          <el-input-number
            v-model="categoryForm.sortnum"
            :step="1"
            :min="0"
            placeholder="数字越大越靠前"
          ></el-input-number>
          <!-- <el-input v-model="categoryForm.sortnum" placeholder="数字越大越靠前"></el-input> -->
        </el-form-item>
        <el-form-item prop="enabled" label="状态">
          <el-radio-group v-model="categoryForm.enabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="关联属性">
          <el-row>基础属性</el-row>
          <el-table
            :data="cateTableData_Base"
            style="width: 100%"
            border
            ref="cateBaseList"
            class="base-table"
            row-key="id"
          >
            <el-table-column prop="attrId" label="ID"></el-table-column>
            <el-table-column prop="title" label="属性名称"></el-table-column>
            <el-table-column prop="required" label="是否必填">
              <template slot-scope="scope">
                {{ scope.row.required ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button class="el-icon-rank"></el-button>
                <el-button type="danger" @click="delAttr(scope.row, scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 0-添加的是基础属性，1-添加的是销售属性 -->
          <el-button type="primary" @click="addAttr(0)">添加基础属性</el-button>
          <el-row>销售属性</el-row>
          <el-table
            :data="cateTableData_Sale"
            style="width: 100%"
            border
            ref="cateSaleList"
            class="sale-table"
            row-key="id"
          >
            <el-table-column prop="attrId" label="ID"></el-table-column>
            <el-table-column prop="title" label="属性名称"></el-table-column>
            <el-table-column prop="required" label="是否必填">
              <template slot-scope="scope">
                {{ scope.row.required ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button class="el-icon-rank"></el-button>
                <el-button type="danger" @click="delAttr(scope.row, scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 0-添加的是基础属性，1-添加的是销售属性 -->
          <el-button type="primary" @click="addAttr(1)">添加销售属性</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">关 闭</el-button>
        <el-button type="primary" @click="saveAll" :loading="saveLoading">保 存</el-button>
      </div>
    </el-dialog>
    <!-- 这里是选择属性 -->
    <el-dialog
      :visible="dialogVisibleSelectAttr"
      title="选择属性"
      width="60%"
      @close="dialogVisibleSelectAttr = false"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <search-list
        ref="attrList"
        :api-url="$url.MallAttrList"
        :option="attrSearchOpt"
        :itemPerRow="6"
        @selection-change="AttrSelectionChange"
        :beforeQuery="beforeQueryAttr"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="title" label="属性名称"></el-table-column>
        <el-table-column prop="unit" label="单位"></el-table-column>
        <el-table-column prop="style" label="填写方式">
          <template slot-scope="scope">
            {{ $selectFormat['goodsMangeInput'](scope.row.style).label }}
          </template>
        </el-table-column>
        <el-table-column prop="required" label="是否必填">
          <template slot-scope="scope">
            {{ scope.row.required ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态">
          <template slot-scope="scope">
            <span>{{ scope.row.enabled ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>
        <div slot="btn-after" class="btn-after">
          <el-button @click="selectMulti">确定选这{{ multipleSelection.length }}个</el-button>
        </div>
      </search-list>
    </el-dialog>
  </div>
</template>
<script>
  import { FormRuleConf } from '@/config';
  import UploadResource from 'comp/UploadResource';
  import Sortable from 'sortablejs';
  export default {
    components: {
      UploadResource,
    },
    computed: {
      // 生成时间上次文件夹
      imgDate: function() {
        return this.dayjs().format('YYYY-MM-DD');
      },
    },
    data() {
      return {
        // 分类多选
        selectedData: [],
        // 属性多选
        multipleSelection: [],
        // dialog显隐
        dialogVisibleCate: false,
        // 选择属性dialog显隐
        dialogVisibleSelectAttr: false,
        // 表单
        categoryForm: {},
        // 表单验证
        ...FormRuleConf.MallCategory,
        // 添加的是基础属性还是默认属性
        kind: '',
        // 基础属性表格
        cateTableData_Base: [],
        // 销售属性表格
        cateTableData_Sale: [],
        // 保存loading
        saveLoading: false,
        // 分类筛选
        searchOpt: [
          {
            type: this.SEARCH_COMP_ENUM.SEARCH_INPUT,
            name: 'title',
            label: '分类名称',
          },
          {
            type: this.SEARCH_COMP_ENUM.SEARCH_INPUT,
            name: 'id',
            label: '分类ID',
          },
        ],
        // 属性筛选
        attrSearchOpt: [
          {
            type: this.SEARCH_COMP_ENUM.SEARCH_INPUT,
            name: 'title',
            label: '属性名称',
          },
          {
            type: this.SEARCH_COMP_ENUM.SEARCH_INPUT,
            name: 'id',
            label: '属性ID',
          },
        ],
      };
    },
    methods: {
      // 删除分类里的属性
      delAttr(row, index) {
        // 没有enabled就是保存在数据库里的，就发请求删除
        // 这里可以代码优化
        if (row.enabled === 1 || row.enabled === 0) {
          if (row.kind) {
            this.cateTableData_Sale = this.cateTableData_Sale.filter(
              (item, inde) => index !== inde,
            );
            this.$message.success('删除成功');
          } else {
            this.cateTableData_Base = this.cateTableData_Base.filter(
              (item, inde) => index !== inde,
            );
            this.$message.success('删除成功');
          }
        } else {
          this.$service
            .MallCategoryAttributeDelete({
              attributeId: row.attrId,
              categoryId: this.categoryForm.id,
            })
            .then((res) => {
              if (row.kind) {
                this.cateTableData_Sale = this.cateTableData_Sale.filter(
                  (item, inde) => index !== inde,
                );
                this.$message.success('删除成功');
              } else {
                this.cateTableData_Base = this.cateTableData_Base.filter(
                  (item, inde) => index !== inde,
                );
                this.$message.success('删除成功');
              }
            });
        }
      },
      // 删除分类
      delItem(row) {
        this.$confirm('确定要将选中的分类从分类列表移除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$service
              .MallCategoryDelete({
                ids: row.id
                  ? row.id
                  : this.selectedData
                      .map((item) => {
                        return item.id;
                      })
                      .join(','),
              })
              .then((res) => {
                this.$message.success('分类移除成功！');
                this.$refs.categoryList.getList();
              });
          })
          .catch(() => {});
      },
      // 编辑
      edit(row) {
        this.$service.MallCategoryDetail({ categoryId: row.id }).then((res) => {
          this.categoryForm = res;
          this.categoryForm.attributeVos.forEach((item) => {
            if (item.kind) {
              this.cateTableData_Sale = item.attributeVos;
            } else {
              this.cateTableData_Base = item.attributeVos;
            }
          });
          this.dialogVisibleCate = true;
          // 因为是dialog所以延后初始化两个表格的拖动
          this.$nextTick(() => {
            this.SeleRowDrop();
            this.BaseRowDrop();
          });
        });
      },
      // 添加分类
      addCate() {
        this.dialogVisibleCate = true;
        // 因为是dialog所以延后初始化两个表格的拖动
        this.$nextTick(() => {
          this.SeleRowDrop();
          this.BaseRowDrop();
        });
      },
      // 添加属性值
      addAttr(val) {
        this.dialogVisibleSelectAttr = true;
        // 0-添加的是基础属性，1-添加的是销售属性
        this.kind = val;
      },
      // 选择多个属性
      selectMulti() {
        this.multipleSelection.forEach((item) => {
          item.kind = this.kind;
          item.attrId = item.id;
          if (this.kind) {
            this.cateTableData_Sale.push(item);
          } else {
            this.cateTableData_Base.push(item);
          }
        });
        // 清空
        this.multipleSelection = [];
        this.dialogVisibleSelectAttr = false;
      },
      // 保存
      saveAll() {
        this.$refs.categoryForm.validate((valid) => {
          if (valid) {
            this.saveLoading = true;
            // 处理数据
            // 排序
            this.cateTableData_Base.forEach((item, index) => {
              item.sortnum = this.cateTableData_Base.length - 1 - index;
            });
            this.cateTableData_Sale.forEach((item, index) => {
              item.sortnum = this.cateTableData_Sale.length - 1 - index;
            });
            this.$service
              .MallCategorySave(
                {
                  ...this.categoryForm,
                  attributeForms: this.cateTableData_Base.concat(this.cateTableData_Sale),
                },
                JSON_HEADER,
              )
              .then((res) => {
                this.saveLoading = false;
                this.dialogVisibleCate = false;
                this.categoryForm = {};
                this.cateTableData_Base = [];
                this.cateTableData_Sale = [];
                this.$message.success('添加分类成功');
                this.$refs.categoryList.getList();
              });
          }
        });
      },
      // dialog关闭
      dialogClose() {
        this.dialogVisibleCate = false;
        this.categoryForm = {};
        this.cateTableData_Base = [];
        this.cateTableData_Sale = [];
        this.$refs.categoryForm.resetFields();
      },
      // 启用禁用
      isOnline(val, status) {
        this.$service
          .MallCategoryStatusToggle({
            id: val.id
              ? val.id
              : this.selectedData
                  .map((item) => {
                    return item.id;
                  })
                  .join(','),
            status: status,
          })
          .then((res) => {
            this.$message.success('操作成功！');
            this.$refs.categoryList.getList();
          });
      },
      // 分类多选
      selectionChange(val) {
        this.selectedData = [...val];
      },
      // 属性多选
      AttrSelectionChange(val) {
        this.multipleSelection = [...val];
      },
      // 销售属性的行拖拽
      SeleRowDrop() {
        // 此时找到的元素是要拖拽元素的父容器
        const tbody = document.querySelector('.sale-table .el-table__body-wrapper tbody');
        const _this = this;
        Sortable.create(tbody, {
          // 指定父元素下可被拖拽的子元素
          draggable: '.el-table__row',
          onEnd({ newIndex, oldIndex }) {
            const currRow = _this.cateTableData_Sale.splice(oldIndex, 1)[0];
            _this.cateTableData_Sale.splice(newIndex, 0, currRow);
          },
        });
      },
      // 基础属性的行拖拽
      BaseRowDrop() {
        // 此时找到的元素是要拖拽元素的父容器
        const tbody = document.querySelector('.base-table .el-table__body-wrapper tbody');
        const _this = this;
        Sortable.create(tbody, {
          // 指定父元素下可被拖拽的子元素
          draggable: '.el-table__row',
          onEnd({ newIndex, oldIndex }) {
            const currRow = _this.cateTableData_Base.splice(oldIndex, 1)[0];
            _this.cateTableData_Base.splice(newIndex, 0, currRow);
          },
        });
      },
      // 筛选之前
      beforeQuery({ searchInfo }) {},
      // 属性筛选之前
      beforeQueryAttr({ searchInfo }) {
        searchInfo.enabled = 1;
      },
    },
  };
</script>
<style lang="less" scoped>
  .avatar {
    display: inline-block;
    width: 39px;
    height: 39px;
    border-radius: 50%;
    vertical-align: middle;
    margin-right: 10px;
  }
  .goods {
    width: 60px;
    height: 60px;
    border-radius: 0px;
  }
  /deep/ .el-dialog {
    .el-input-number {
      width: 290px;
    }
  }
</style>
